# pita: An invisible audio player
# Copyright (C) 2006-2007 Austin Bingham
#
# This program is free software# you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation# either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program# if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# You can reach the author at:
#     austin.bingham@gmail.com

import pyxiph.ao as ao
import logging

driver_name = ''
driver_options = []
logger = logging.getLogger('pita.decoder')

class CTORError:
    """
    This is the exception thrown if a Decoder subclass
    has an error in construction.
    """
    def __init__(self, msg):
        self.msg = msg

class Decoder:
    OK       = 0
    FINISHED = 1
    ERROR    = 2

    def __init__(self):
        self.device = None
        self._rate = ao.Format.default_rate

    def init_device(self):
        '''
        override this to provide a decoder-specific device
        initialization.
        '''
        if not driver_name:
            logger.info('driver = default')
            driver_id = ao.default_driver_id()
        else:
            logger.info('driver = %s' % driver_name)
            driver_id = ao.driver_id(driver_name)

        logger.info('driver_options = %s' % driver_options)

        return ao.Device(driver_id,
                         ao.Format(rate=self.sample_rate),
                         driver_options)

    def play_chunk_impl(self):
        """
        This is called to ask the decoder to play the
        next chunk of the file (whatever that means).

        This should return one of the following values:
           Decode.OK if the chunk was played normally
           Decode.FINISHED if end of file has been reached
           Decode.ERROR if there is some error that
           terminates playback
        """
        return Decoder.FINISHED

    def _set_sample_rate(self, r):
        self._rate = r
        if self.device:
            self.device.set_sample_rate(r)
        # TODO: Do we need to explicitly close the device? Or will standard garbage collection suffice?

    def _get_sample_rate(self):
        return self._rate

    sample_rate = property(_get_sample_rate, _set_sample_rate,
                           'Controls the sample-rate of the decoder')

    def play_chunk(self):
        if not self.device:
            self.device = self.init_device()
        return self.play_chunk_impl()
